<?php 
/**
 * 车辆管理类
 * @Author    紫梦
 * @DateTime  2017-11-03
 * @copyright 响响租车
 * @version   1.0
 * @UpdateTime 2017-11-10
 */
namespace app\wxapp\controller;
use think\Exception;
use think\Request;
use think\Db;
use app\common\model\Agency;
use app\common\model\Company;
use app\common\model\CarType;
use app\common\model\Brand;
use app\common\model\Cars as CarsModel;
use app\common\model\CarInfo;
use app\common\model\Yyyymmdd;
use app\common\request\ClientLai;
use app\common\request\Oss;
use app\common\controller\Gps;
use app\common\model\Terminal as TerminalModel;

class CarsTemp extends Base
{
    /**
     *车辆列表
     */
    public function index()
    {       
        $request = Request::instance();
        $post = $request->post();

        if( !empty($post['datemin']) && !empty($post['datemax']) ){
            $where['create_time'] = ['between time',[$post['datemin'],$post['datemax']]];                  
                
        }
        if ( empty($post['datemin']) && !empty($post['datemax']) ){             
            $where['create_time'] = ['<= time',$post['datemax']];
                
                
        }
        if ( !empty($post['datemin']) && empty($post['datemax']) ) {
            $where['create_time'] = ['> time',$post['datemin']];
             
        }
        if ( !empty($post['search_input']) ) {
            $where['car_sn|car_unique_id|cardcode|equipment_id'] = ['like','%'.$post['search_input'].'%'];
                
        }
        if ( !empty($post['relevance']) ) {
            $where['relevance'] = $post['relevance'];     
                
        }
        if ( !empty($post['agency_id']) ) {
            $where['agency_id'] = $post['agency_id'];
                
        }
        if ( !empty($post['brand_id']) ) {
            $where['brand_id'] = $post['brand_id'];
                
        }
        if ( !empty($post['supplier_no']) ) {
            $where['supplier_no'] = $post['supplier_no'];
                
        }
        
        if( empty($where) ){
            $where = '1=1';
        }        
        try {           
            $data = CarsModel::where($where)
                        ->order('car_id', 'desc')
                        ->paginate($post['length'],false,[
                                'type'     => 'bootstrap',
                                'var_page' => 'page',
                                'page'=>$post['page'] ,
                            ]);             
        } catch (\Exception $e) {
            
            return [
                'code'=>2,
                'msg'=>$e->getMessage(),
                ];

        }
        return $data;
    }

    public function add()
    {
        $request = Request::instance();
        if($request->isPost()){
            $data = $request->post();
            $model = new CarsModel();           

            $validate = validate('Cars');

            if(!$validate->check($data)){
                return [
                    'code'=>2,
                    'msg'=>$validate->getError(),
                ];
            }
            try {
                $model->allowField(true)->save($data);
                $id =$model->car_id;                                
            } catch (Exception $e) {
                return [
                    'code'=>3,
                    'msg'=>$e->getMessage(),
                ];
            }
            if($id){
                return [
                    'code'=>1,
                    'id' => $id,
                    'msg'=>'添加成功'
                    ];
            
            }else{
                return [
                    'code'=>2,
                    'msg'=>'添加失败,请稍后再试'
                    ];
            }
        }else{
            $data['brand'] = Brand::field('id,name')->select();
            $data['holder'] = Company::field('id,name')->select();
            $data['type'] = CarType::field('id,name')->select();
            $data['agency'] = Agency::where('id','>',1)->field('id,name')->select();

            return $data;  

        }
    }

    public function edit()
    {
        $request = Request::instance();
        if($request->isPost()){
            $data = $request->post();
            $model = new CarsModel();           

            try {
                                            
                $result = $model->allowField(true)->validate(true)->save($data,['car_id' => $data['car_id']]);
            } catch (Exception $e) {
                return [
                    'code'=>3,
                    'msg'=>$e->getMessage(),
                ];
            }
            if(false === $result){
                // 验证失败 输出错误信息
                return [
                    'code'=>2,
                    'msg'=>$validate->getError(),
                ];
            }
            
            return [
                'code'=>1,
                'msg'=>'更新成功'
                ];
            
            
        }else{
            $data['brand'] = Brand::field('id,name')->select();
            $data['holder'] = Company::field('id,name')->select();
            $data['type'] = CarType::field('id,name')->select();
            $data['agency'] = Agency::where('id','>',1)->field('id,name')->select();
            
            return $data;  

        }
    }   

    /**
     * 车辆详情页
     */
    public function details($id=1)
    {
        
        try {           
            $data = CarsModel::with('brand,agency')->find($id);
            $bolutu = Yyyymmdd::where('car_unique_id',$data['car_unique_id'])->cache(60)->find();
            $carInfo = CarInfo::get($data['car_unique_id']);
            if($bolutu!=null){
                $result = Gps::geocode($bolutu['longitude'],$bolutu['latitude']);
                if($result){
                    $gaodeapi = json_decode($result,true);            
                }else{
                    $gaodeapi = null;
                }
            }elseif($carInfo['supplier_no']!=null){
                $result = Gps::geocode($carInfo['longitude'],$carInfo['latitude']);
                if($result){
                    $gaodeapi = json_decode($result,true);            
                }else{
                    $gaodeapi = null;
                }
            }else{
                $gaodeapi = null;
            }            
        } catch (\Exception $e) {
            
            return [
                'code'=>2,
                'msg'=>$e->getMessage(),
                ];
        }
        $data ->car_file;
        $data['holder_name'] = $data->holder_name;
        $data['agency_name'] = $data->agency['name'];
        $data['brand_name'] = $data->brand['name'];
        $data['bolutu_data'] = $bolutu;
        $data['car_info_data'] = $carInfo;
        $data['gaodeapi'] = $gaodeapi;
        return $data;
    }

    // 添加附件
    public function add_file()
    {   
        $request = Request::instance();
        $id = $request->post('id');
        $type = $request->post('type');
        $file = $request->file('uploadfile');
        if($file){
            $oss = new Oss();
           
            $url = $oss->uploadOss($file);                    
            if($url){
                try {
                    Db::name('car_file')->insert(['car_id'=>$id,'file_type'=>$type,'file_url'=>$url]);
                    
                } catch (Exception $e) {
                    return [
                        'code'=>2,
                        'msg'=>$e->getMessage(),
                        ];
                }
            }
            
        } 
        return [
            'code'=>1,
            'msg'=>'上传成功'
            ];
    }

    /**
     * 删除车辆
     */
    public function delete($id)
    {
        $msg['code'] = 1;
        $msg['msg'] = '删除成功';
        $data = CarsModel::get($id);
        if($data['band_status'] == 1){
            $msg['code'] = 3; 
            $msg['msg'] = '删除失败,请解除绑定';
            return $msg;
        }
        try {
            CarsModel::destroy($id);
        } catch (Exception $e) {
            return [
                'code'=>2,
                'msg'=>$e->getMessage()
                ];
        }
        
        return $msg;
    }


    /**
     * 绑定车辆
     */
    public function bind_car($id)
    {
        $model = CarsModel::get($id);
        if($model['supplier_no'] == 1376920002){
            $config = config('blt_lai');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $data['supplier_no'] = $model['supplier_no'];
            $data['car_unique_id'] = $model['car_unique_id'];
            $data['equipment_id'] = $model['equipment_id'];
            $data['bluetooth_id'] = ltrim($model['equipment_id'],0);
            $data['license_plate'] = $model['car_sn'];
            
            $res = $obj->request_post(rtrim($config['url'],'/').'/bind_car',$data);

            $arr = json_decode($res,true);


            if($arr['result']==0){          
                try{
                    $model->band_status = 1;
                    $model->save();
                    
                }catch(\Exception $e){
                    $arr['result'] = 1;
                    $arr['msg'] = '绑定成功,但是数据库状态更新失败';
                }

            }
            return $arr; 

        }elseif($model['supplier_no'] == 1376920003){
            $config = config('local_iot');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $data['supplierNo'] = 1376920002;
            $data['carUniqueId'] = $model['car_unique_id'];
            $data['machineNum'] = $model['equipment_id'];
            $data['deviceName'] = $model['equipment_id'];
            $data['licensePlate'] = $model['car_sn'];
            $res = $obj->request_post(rtrim($config['url'],'/').'/car/bindCar',$data);

            $arr = json_decode($res,true);

            if($arr['result']==0){          
                try{
                    $model->band_status = 1;
                    $model->save();
                    
                }catch(\Exception $e){
                    $arr['result'] = 1;
                    $arr['msg'] = '绑定成功,但是数据库状态更新失败';
                }

            }
            return $arr;
        }
        
    }

    /**
     * 解绑车辆
     */
    public function unbind_car($id)
    {

        $model = CarsModel::get($id);
        if($model['supplier_no'] == 1376920002){
            $config = config('blt_lai');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $data['supplier_no'] = $model['supplier_no'];
            $data['car_unique_id'] = $model['car_unique_id'];
            
            $res = $obj->request_post(rtrim($config['url'],'/').'/unbind_car',$data);

            $arr = json_decode($res,true);


            if($arr['result']==0){          
                try{
                    $model->band_status = 0;
                    $model->save();
                    
                }catch(\Exception $e){
                    $arr['result'] = 1;
                    $arr['msg'] = '解绑成功,但是数据库状态更新失败';
                }

            }
            return $arr;
            
        }elseif($model['supplier_no'] == 1376920003){
            $config = config('local_iot');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $data['supplierNo'] = 1376920002;
            $data['carUniqueId'] = $model['car_unique_id'];
            $res = $obj->request_post(rtrim($config['url'],'/').'/car/unbindCar',$data);

            $arr = json_decode($res,true);

            if($arr['result']==0){          
                try{
                    $model->band_status = 0;
                    $model->save();
                    
                }catch(\Exception $e){
                    $arr['result'] = 1;
                    $arr['msg'] = '解绑成功,但是数据库状态更新失败';
                }

            }

            return $arr;
        }
    }
    /**
     * 删除附件
     */
    public function del_file($id)
    {
        
        $url = Db::name('car_file')->where(['id'=>$id])->find();
        $oss = new Oss();
        $res = false;
        if($oss->unlinkOss($url['file_url'])){
           
            try {
                Db::name('car_file')->delete($id);
            } catch (Exception $e) {
                return [
                    'code'=>2,
                    'msg'=>$e->getMessage(),
                    ];
            }
            
        }
        return [
            'code'=>1,
            'msg'=>'删除成功'
            ];
    }

    public function ajaxGetTerminal($query = 0)
    {
        $where = '%'.$query.'%';

        $data = TerminalModel::where('equipment_id','like',$where)->limit(8)->select();

        return $data;
    }


}